package com.haoran.dwz.common.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

/** 
 * 登录失败控制 
 *  
 * @date 2016年12月20日 
 */  
@Component
public class UsmAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {  
	
	public UsmAuthenticationFailureHandler() {
		this("/login?error=true");
	}
	
	public UsmAuthenticationFailureHandler(String failureUrl) {
		super(failureUrl);
	}

	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		//保存错误次数
		Object failtureTimes = request.getSession().getAttribute(UsmInitializationFilter.SESSION_USM_LOGIN_FAILURE_TIMES_KEY);
		Integer times = 1;
		if(null == failtureTimes) {
			request.getSession().setAttribute(UsmInitializationFilter.SESSION_USM_LOGIN_FAILURE_TIMES_KEY,times);
		}else {
			times = Integer.valueOf(failtureTimes.toString())+1;
			request.getSession().setAttribute(UsmInitializationFilter.SESSION_USM_LOGIN_FAILURE_TIMES_KEY,times);
		}
		super.onAuthenticationFailure(request, response, exception);
	}
}  